package com.lanyou.cook.config;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;


public class OwnPermissionsAuthorizationFilter  extends PermissionsAuthorizationFilter{
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

		HttpServletRequest  httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = httpRequest.getHeader("Referer");
		String url = httpRequest.getRequestURI();
		if(StringUtils.isNoneBlank(url)){
			if(url.indexOf("/kettleAPI") != -1 || url.indexOf("api/dataMaintenance") != -1 || url.indexOf("api/logout") != -1){
				return true;
			}
		}
		if(StringUtils.isNoneBlank(uri)){
			if(uri.indexOf("UserRegistration.html") != -1 || uri.indexOf("PassRetrieve.html") != -1
					|| uri.indexOf("UserLogin.html") != -1){
				return true;
			}
		}
		
        Subject subject = getSubject(request, response);
        if(!subject.isAuthenticated()){
        	httpResponse.setHeader("sessionStatus", "timeout");
			return true;
		}
        
        String[] perms = (String[]) mappedValue;
        
        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }

        return isPermitted;
    }
}
